<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入优惠券ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有门槛" prop="isThreshold">
        <el-select v-model="queryParams.isThreshold" placeholder="请选择是否有门槛" clearable>
          <el-option
            v-for="dict in is_has_threshold"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="过期日期" prop="expireDate">
        <el-date-picker clearable
          v-model="queryParams.expireDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择过期日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qth:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qth:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qth:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['qth:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券ID" align="center" prop="id" />
      <el-table-column label="优惠券名称" align="center" prop="name" />
      <el-table-column label="是否有门槛" align="center" prop="isThreshold">
        <template #default="scope">
          <dict-tag :options="is_has_threshold" :value="scope.row.isThreshold"/>
        </template>
      </el-table-column>
      <!-- “门槛”，“优惠”，表单中除以100回显 -->
      <el-table-column label="门槛(单位：元)" align="center" prop="atLeast">
        <template #default="scope">
          {{ formatAmount(scope.row.atLeast) }}
        </template>
      </el-table-column>
      <el-table-column label="优惠(单位：元)" align="center" prop="amount">
        <template #default="scope">
          {{ formatAmount(scope.row.amount) }}
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="剩余数量" align="center" prop="remainingQuantity" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期日期" align="center" prop="expireDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-space direction="vertical" :size="8" align="start">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qth:coupon:edit']">修改</el-button>
            <el-button link type="primary" icon="ToiletPaper" @click="handleSend(scope.row)" v-hasPermi="['qth:coupon:issue']">发放</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qth:coupon:remove']">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="是否有门槛" prop="isThreshold">
          <el-select v-model="form.isThreshold" placeholder="请选择是否有门槛">
            <el-option
              v-for="dict in is_has_threshold"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门槛(单位：元)" prop="atLeast">
          <el-input v-model="form.atLeast" placeholder="请输入门槛(单位：元)" />
        </el-form-item>
        <el-form-item label="优惠(单位：元)" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入优惠(单位：元)" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="剩余数量" prop="remainingQuantity">
          <el-input v-model="form.remainingQuantity" placeholder="请输入剩余数量" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过期日期" prop="expireDate">
          <el-date-picker clearable
            v-model="form.expireDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择过期日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发放优惠券弹窗 -->
    <el-dialog :title="`优惠券发放:${ currentCoupon.name || ''}`" v-model="issueDialogVisible" width="1300px" append-to-body @close="resetIssueForm">
      <el-form :model="issueQueryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户ID" prop="id">
          <el-input
            v-model="issueQueryParams.id"
            placeholder="请输入用户ID"
            clearable
            @keyup.enter="getUsersList"
          />
        </el-form-item>
        <el-form-item label="用户姓名" prop="username">
          <el-input
            v-model="issueQueryParams.username"
            placeholder="请输入用户姓名"
            clearable
             @keyup.enter="getUsersList"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="issueQueryParams.phone"
            placeholder="请输入用户电话"
            clearable
            @keyup.enter="getUsersList"
          />
        </el-form-item>
        <el-form-item label="注册时间" prop="registerTime">
          <el-date-picker clearable
            v-model="issueQueryParams.registerTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择注册时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getUsersList">搜索</el-button>
          <el-button icon="Refresh" @click="resetIssueQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="usersLoading" :data="usersList" @selection-change="handleUsersChange">
        <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户ID" align="center" prop="id" />
          <el-table-column label="用户姓名" align="center" prop="username" />
          <el-table-column label="联系电话" align="center" prop="phone" />
          <el-table-column label="注册时间" align="center" prop="registerTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
      </el-table>
        <!-- 分页 -->
        <pagination
        v-show="usersTotal > 0"
        :total="usersTotal"
        v-model:page="issueQueryParams.pageNum"
        v-model:limit="issueQueryParams.pageSize"
        @pagination="getUsersList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openRecord" >发放记录</el-button>
          <el-button type="primary" @click="submitFormCoupon">发 放</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发放记录弹窗 -->
     <el-dialog :title="`${currentCoupon.name || ''} 发放记录`" v-model="recordDialogVisible" width="1000px" append-to-body>
      <el-table v-loading="recordLoading" :data="recordList">
        <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="优惠券" align="center" prop="couponName" />
          <el-table-column label="用户姓名" align="center" prop="username" />
          <el-table-column label="联系电话" align="center" prop="phone" />
          <el-table-column label="是否使用" align="center" prop="isUsed">
            <template #default="scope">
              <dict-tag :options="is_has_threshold" :value="scope.row.isUsed"/>
            </template>
          </el-table-column>
          <el-table-column label="领取时间" align="center" prop="receiveTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
      </el-table>
      <!-- 发放记录分页 -->
      <pagination
        v-show="recordTotal > 0"
        :total="recordTotal"
        v-model:page="recordQueryParams.pageNum"
        v-model:limit="recordQueryParams.pageSize"
        @pagination="getRecordList"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/qth/coupon";
import { listUsers } from "@/api/qth/users.js"
import { BatchAddCouponUser, listCouponUser } from "@/api/qth/couponUser.js";
import { reactive, ref } from "vue";
import { formatAmount } from "@/utils/amountUtil.js"

const { proxy } = getCurrentInstance();
const { is_has_threshold } = proxy.useDict('is_has_threshold');


const couponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const issueDialogVisible  = ref(false);
const currentCoupon = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    name: null,
    isThreshold: null,
    expireDate: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

//新增：用户列表相关变量
const usersList = ref([]); //用户列表数据
const usersTotal = ref(0); //用户总数
const usersLoading = ref(false); //用户列表加载状态
const issueQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  id: null,
  username: null,
  phone: null,
  openId: null,
  registerTime: null
})

//新增:发放记录列表相关变量
const recordDialogVisible = ref(false);
const recordList = ref([]); // 发放记录列表数据
const recordTotal = ref(0); // 发放记录总数
const recordLoading = ref(false); //发放记录列表加载状态
const recordQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  couponId: null
})

/** 查询优惠券列表列表 */
function getList() {
  loading.value = true;
  listCoupon(queryParams.value).then(response => {
    couponList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    isThreshold: null,
    atLeast: null,
    amount: null,
    quantity: null,
    remainingQuantity: null,
    createTime: null,
    startDate: null,
    expireDate: null
  };
  proxy.resetForm("couponRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 发放优惠多选框选中数据
function handleUsersChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加优惠券列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCoupon(_id).then(response => {
    form.value = response.data;
    const couponData = response.data;
    // 处理“门槛”和“优惠”字段，除100后回显
    form.value = {
      ...couponData,
      atLeast: formatAmount(couponData.atLeast || 0), 
      amount: formatAmount(couponData.amount || 0) 
    }
    open.value = true;
    title.value = "修改优惠券列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate(valid => {
    if (valid) {
      const submitData = { ...form.value };
      submitData.amount = Number(submitData.amount) * 100;
      submitData.atLeast = Number(submitData.atLeast) * 100;
      if (form.value.id != null) {
        updateCoupon(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoupon(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除优惠券列表编号为"' + _ids + '"的数据项？').then(function() {
    return delCoupon(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('qth/coupon/export', {
    ...queryParams.value
  }, `coupon_${new Date().getTime()}.xlsx`)
}

/** 发放优惠券操作弹窗  */
function handleSend(row) {
  getUsersList();
  currentCoupon.value = row;
  issueDialogVisible .value = true;
}

/* 查询用户列表方法 */
function getUsersList() {
  usersLoading.value = true;
  listUsers(issueQueryParams).then(response => {
    console.log("查询用户列表:", response);
    usersList.value = response.rows;
    usersTotal.value = response.total;
    usersLoading.value = false;
  })
}

/* 重置查询参数方法 */
function resetIssueQuery() {
  issueQueryParams.id = null;
  issueQueryParams.username = null;
  issueQueryParams.openId = null;
  issueQueryParams.phone = null;
  issueQueryParams.registerTime = null;
  issueQueryParams.pageNum = 1;
  getUsersList();
}

/** 发放优惠券提交按钮 */
function submitFormCoupon() {
  if(ids.value.length === 0){
    proxy.$modal.msgWarning("请选择要发放的用户");
    return;
  }
  //整合数据
  const batchAddReq = {
    couponId:currentCoupon.value.id,
    userIds: ids.value
  };
  BatchAddCouponUser(batchAddReq).then(() => {
    proxy.$modal.msgSuccess("发放成功");
    issueDialogVisible.value = false;
    resetIssueForm();
    getList();
  }).catch(() => {
    proxy.$modal.msgError("发放失败");
  })
}

// 重置发放弹窗表单
function resetIssueForm() {
  ids.value = [];
  issueQueryParams.pageNum = 1;
  usersList.value = [];
}

//发放记录操作弹窗
function openRecord() {
  recordQueryParams.couponId = currentCoupon.value.id;
  recordQueryParams.pageNum = 1;
  getRecordList();
  recordDialogVisible.value = true;
}

//查询发放记录列表
function getRecordList() {
  recordLoading.value = true;
  listCouponUser(recordQueryParams).then(response => {
    recordList.value = response.rows;
    recordTotal.value = response.total;
    recordLoading.value = false;
  }).catch(() => {
    recordLoading.value = false;
  });
}

getList();
</script>

<style scoped>
.dialog-footer {
  display: flex; 
  justify-content: space-between; 
}
</style>